<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/Reports' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card class="box-card" style="margin-top: 20px">
      <!-- 警告 -->
      <el-alert title="添加商品信息" type="info" show-icon center> </el-alert>
      <!-- 步骤条 -->
      <el-steps
        :active="activeIndex - 0"
        finish-status="success"
        align-center
        style="margin-top: 20px"
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 标签页 -->
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm">
        <el-tabs
          tab-position="left"
          style="margin-top: 20px"
          v-model="activeIndex"
          :before-leave="beforeLeave"
          @tab-click="tabClick"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="ruleForm.goods_name"></el-input>
            </el-form-item>

            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="ruleForm.goods_price"></el-input>
            </el-form-item>

            <el-form-item label="商品重量" prop="goods_weight">
              <el-input
                type="number"
                v-model="ruleForm.goods_weight"
              ></el-input>
            </el-form-item>

            <el-form-item label="商品数量" prop="goods_number">
              <el-input
                v-model="ruleForm.goods_number"
                type="number"
              ></el-input>
            </el-form-item>

            <el-form-item label="商品分类" prop="goods_cat"
              ><br />
              <el-cascader
                v-model="ruleForm.goods_cat"
                :options="options"
                :props="{
                  expandTrigger: 'hover',
                  label: 'cat_name',
                  value: 'cat_id',
                  children: 'children',
                }"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              :label="item.attr_name"
              v-for="item in manyList"
              :key="item.attr_id"
              ><br />

              <el-checkbox
                :label="value"
                border
                v-for="(value, index) in item.attr_vals"
                :key="index"
                @change="checkboxClick(item.attr_id, value, $event)"
              ></el-checkbox>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :label="item.attr_name"
              v-for="item in onlyList"
              :key="item.attr_id"
            >
              <el-input v-model="item.attr_vals"> </el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              action="http://heima.9yuecloud.com:9988/api/private/v1/upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :headers="headers"
              :on-success="handleSuccess"
              list-type="picture"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor class="ql-editor" v-model="ruleForm.goods_introduce">
            </quill-editor>
            <el-button
              type="primary"
              style="margin-left: 15px"
              @click="addGoods"
              >添加商品</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 预览图片弹框 -->
    <el-dialog title="图片预览" :visible.sync="dialogVisible" width="50%">
      <img :src="previewImgPath" style="width: 100%" />
    </el-dialog>
  </div>
</template>

<script>
import _ from "lodash";
export default {
  name: "MyVueGoodsAdd",

  data() {
    return {
      activeIndex: "0",
      ruleForm: {
        goods_name: "",
        goods_price: "",
        goods_number: 0,
        goods_weight: 0,
        // 商品所属分类数组
        goods_cat: "",
        // 动态参数复选框的状态
        attrs: [],
        // 图片的数组
        pics: [],
        // 富文本编辑内容
        goods_introduce: "",
      },
      //   正则校验
      rules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        goods_cat: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
      },
      // 商品分类列表
      options: [],
      // 动态参数列表
      manyList: [],
      // 静态参数列表
      onlyList: [],
      // 上传图片的头
      headers: {
        Authorization: sessionStorage.getItem("token"),
      },
      // 预览图片的弹框标识
      dialogVisible: false,
      // 预览图片的路径
      previewImgPath: "",
    };
  },

  mounted() {
    this.list();
  },

  methods: {
    // 渲染商品分类列表
    list() {
      this.$http.get(`categories`, { params: { type: 3 } }).then((res) => {
        if (res.data.meta.status == 200) {
          this.options = res.data.data;
        }
      });
    },

    //  商品分类列表没有选择内容不允许跳转
    beforeLeave() {
      if (this.ruleForm.goods_cat.length == 0) {
        this.$message.error("请选择商品分类");
        return false;
      } else {
        return true;
      }
    },

    // 获取动态参数列表
    tabClick() {
      if (this.activeIndex == 1) {
        this.$http
          .get(`categories/${this.paramsId}/attributes`, {
            params: { sel: "many" },
          })
          .then((res) => {
            if (res.data.meta.status == 200) {
              res.data.data.forEach((item) => {
                if (item.attr_vals == "") {
                  item.attr_vals = [];
                } else {
                  item.attr_vals = item.attr_vals.split(" ");
                }
              });
              this.manyList = res.data.data;
            }
          });
      } else if (this.activeIndex == 2) {
        this.$http
          .get(`categories/${this.paramsId}/attributes`, {
            params: { sel: "only" },
          })
          .then((res) => {
            if (res.data.meta.status == 200) {
              res.data.data.forEach((item) => {
                this.onlyList = res.data.data;
              });
            }
          });
      }
    },
    // 选择动态属性的复选框
    checkboxClick(attr_id, attr_value, e) {
      if (e === true) {
        this.ruleForm.attrs.push({ attr_id, attr_value });
      } else {
        let index = this.ruleForm.attrs.findIndex((item) => {
          return item.attr_value == attr_value;
        });
        this.ruleForm.attrs.splice(index, 1);
      }
    },
    // 图片上传成功之后触发
    handleSuccess(response) {
      if (response.meta.status === 200) {
        // 图片的临时路径
        const imgpath = {
          pic: response.data.tmp_path,
        };
        // 将图片信息push数组里
        this.ruleForm.pics.push(imgpath);
        this.$message.success(response.meta.msg);
      } else {
        this.$message.error(response.meta.msg);
      }
    },
    // 处理图片预览
    handlePreview(file) {
      this.dialogVisible = true;
      this.previewImgPath = file.url;
    },
    // 移除图片
    handleRemove(file) {
      // 获取删除图片的临时路径
      let delImgPath = file.response.data.tmp_path;
      // 从图片的数组里边找下标
      let index = this.ruleForm.pics.findIndex(
        (item) => item.tmp_path === delImgPath
      );
      this.ruleForm.pics.splice(index, 1);
    },
    // 添加商品
    addGoods() {
      // 深拷贝
      let ruleForm = _.cloneDeep(this.ruleForm);
      ruleForm.goods_cat = ruleForm.goods_cat.join(",");
      // 将静态属性动态参数整合到一起
      let str = this.onlyList.map((item) => {
        return { attr_id: item.attr_id, attr_value: item.attr_vals };
      });
      ruleForm.attrs.push(...str);
      // 请求接口添加商品
      this.$http.post(`goods`, ruleForm).then((res) => {
       
        if (res.data.meta.status == 201) {
          this, this.$message.success(res.data.meta.msg);
          this.list();
        }else{
          this.$message.error(res.data.meta.msg)
        }
      });
    },
  },
  computed: {
    // 分类id
    paramsId() {
      if (this.ruleForm.goods_cat.length != 3) {
        return;
      } else {
        return this.ruleForm.goods_cat[this.ruleForm.goods_cat.length - 1];
      }
    },
  },
};
</script>

<style lang="scss" scoped>
</style>